package com.it.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.eduservice.entity.EduSubject;
import com.it.eduservice.entity.excel.SubjectData;
import com.it.eduservice.entity.subject.OneSubject;
import com.it.eduservice.entity.subject.TwoSubject;
import com.it.eduservice.listener.SubjectExcelListener;
import com.it.eduservice.mapper.EduSubjectMapper;
import com.it.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author test.java
 * @since 2021-01-20
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try{
            //文件输入流
            InputStream in=file.getInputStream();
            //调用方法读取
            EasyExcel.read(in,SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    //课程分类列表（树形）
    public List<OneSubject> getAllOneTwoSubject() {
        //查询一级分类
        QueryWrapper<EduSubject>wrapperOne=new QueryWrapper<EduSubject>();
        wrapperOne.eq("parent_id",0);
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);

        //查询二级分类
        QueryWrapper<EduSubject>wrapperTwo=new QueryWrapper<EduSubject>();
        wrapperTwo.ne("parent_id",0);
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        //封装一级分类
        List <OneSubject>finalSubjectList=new ArrayList<OneSubject>();
        for (int i = 0; i < oneSubjectList.size(); i++) {
            EduSubject eduSubject = oneSubjectList.get(i);
            OneSubject oneSubject=new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubject);
            finalSubjectList.add(oneSubject);
            //在一级分类中遍历二级分类
            List<TwoSubject>twoFinalSubjectList=new ArrayList<TwoSubject>();
            for (int m = 0; m < twoSubjectList.size(); m++) {
                //获取二级分类
                EduSubject tSubject = twoSubjectList.get(m);
                //判断二级分类的parent_id和一级分类的id是否相等
                if(tSubject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject=new TwoSubject();
                    BeanUtils.copyProperties(tSubject,twoSubject);
                    twoFinalSubjectList.add(twoSubject);
                }
            }
            //把二级分类放到一级分类中
            oneSubject.setChildren(twoFinalSubjectList);
        }
        return finalSubjectList;
    }
}
